package com.dream.service.recommender.util;

import com.alibaba.fastjson.JSONObject;
import com.dream.service.recommender.domain.model.ClickStreamExtraValue;
import com.dream.service.recommender.domain.model.UserInfo;
import com.dream.service.recommender.domain.request.FrontParam;
import com.dream.service.recommender.domain.response.*;
import com.dream.service.recommender.toolkits.utils.SHA1;
import com.dream.service.recommender.toolkits.utils.StringUtils;
import java.util.*;


/**
 *  Created by zhiji on 2016/5/17.
 */
public class MercuryUrlManager {

    private static String defaultUrl = "https://clk.motif.me/log.gif";
    private static String replace = "https://clk.motif.me";

    /*http://clk.motif.me/log.gif?t=rec.700001&m=OPEN_M2016-1&pin=&uuid=&v={ "action": 0, "sku": 1111, "csku": 525660, "index": 0, "expid": 0 }*/
    /**
     * 生成请求url  暂时无用
     * @param requestParam
     * @param recommenderData
     * @return
     */
    public static String getReqUrl(FrontParam requestParam, RecommenderData<RecommenderItem> recommenderData) {
        String recID = requestParam.getRec_id();
        StringBuilder url = new StringBuilder(defaultUrl);
        url.append("?t=rec.").append(recID);
        String os = requestParam.getOs();
        String _ref = "&m=OPEN_M2016-1";
        if (!StringUtils.isEmpty(os)) {
            if (os.toLowerCase().equals("ios")) {
                _ref = "&m=ios_m2016-1";
            } else if (os.toLowerCase().equals("android")) {
                _ref = "&m=android_m2016-1";
            } else if (os.toLowerCase().equals("h5")) {
                _ref = "&m=h5_m2016-1";
            } else if (os.toLowerCase().equals("pc")) {
                _ref = "&m=pc_m2016-1";
            }
        }
        url.append(_ref);
        UserInfo user = requestParam.getUser();
        if (user != null) {
            url.append("&pin=").append(user.getPin() == null ? "" : user.getPin());
            url.append("&uuid=").append(user.getUuid() == null ? "" : user.getUuid());
        }
        ClickStreamExtraValue clickStreamExtraValue = new ClickStreamExtraValue(0);
        if (requestParam.getSpu() != null) {
            clickStreamExtraValue.setSpu(requestParam.getSpu());
        }
        if (requestParam.getSpus() != null && !requestParam.getSpus().isEmpty()) {
            clickStreamExtraValue.setSpus(requestParam.getSpus().toArray(new Long[requestParam.getSpus().size()]));
        }
        if (recommenderData != null) {
            List<RecommenderItem> recommendItemList = recommenderData.getList();
            if (recommendItemList != null && !recommendItemList.isEmpty()) {
                List<Long> cspus = new ArrayList<Long>();
                List<Integer> ctopicIds = new ArrayList<Integer>();
                for (int i = 0; i < recommendItemList.size(); i++) {
                    try {
                        RecommenderItem item = recommendItemList.get(i);
                        switch (item.getRec_type()) {
                            case 1 : cspus.add(((RecommenderSku) item).getSpu()); break;
                            case 2 : ctopicIds.add(((RecommenderTopic)item).getTopic_id()); break;
                            case 3 : break;
                            case 4 : cspus.add(((RecommenderShopifyProduct)item).getProduct_id()); break;
                            default: break;
                        }
                    } catch (Exception e) {}
                }
                if (!cspus.isEmpty()) {
                    clickStreamExtraValue.setCspus(cspus.toArray(new Long[cspus.size()]));
                }
                if (!ctopicIds.isEmpty()) {
                    clickStreamExtraValue.setCtopicIds(ctopicIds.toArray(new Integer[ctopicIds.size()]));
                }
            }
        }
        if (!StringUtils.isEmpty(requestParam.getOs())) {
            clickStreamExtraValue.setOs(requestParam.getOs());
        }
        if (!StringUtils.isEmpty(requestParam.getVersion())) {
            clickStreamExtraValue.setVer(requestParam.getVersion());
        }
        clickStreamExtraValue.setExpid(recommenderData.getExp_id());
        url.append("&v=").append(JSONObject.toJSONString(clickStreamExtraValue));
        return sigUrl(url.toString());
    }

    /**
     * URL 签名
     * @param url
     * @return
     */
    private static String sigUrl(String url) {
        if (StringUtils.isEmpty(url)) {
            return url;
        }
        StringBuilder message = new StringBuilder(url);
        String sha1 = SHA1.encode(message.toString().replace(replace, ""));
        return url + "&sig=" + sha1;
    }

    //发送展示
    public static void setMercuryUrl(RecommenderData<RecommenderItem> recommenderData, FrontParam requestParam) {
        List<RecommenderItem> items = recommenderData.getList();
        if (items == null || items.isEmpty()) {
            return;
        }
        String recID = requestParam.getRec_id();
        int expid = recommenderData.getExp_id();
        UserInfo user = requestParam.getUser();
        String os = requestParam.getOs();
        String version = requestParam.getVersion();
        Long spu = requestParam.getSpu();
        List<Long> spus = requestParam.getSpus();
        Integer frontCid = requestParam.getCid();
        for (RecommenderItem item : items) {
            /*RecommenderItem item = items.get(i);*/
            //点击
            String cUrl = packageUrl(recID, spu, spus, frontCid, user, item, expid, os, version, item.getPos(), 1);
            //展示
            String iUrl = packageUrl(recID, spu, spus, frontCid, user, item, expid, os, version, item.getPos(), 0);
            item.setClk(sigUrl(cUrl));
            item.setImpr(sigUrl(iUrl));
        }
        //总的展示
        String iUrls = packageWholeImplUrl(recID, spu, spus, frontCid, user, items, expid, os, version, 0);
        recommenderData.setImpr(sigUrl(iUrls));
    }

    //生成点击url
    private static String packageUrl(String rec_id, Long spu, List<Long> spus, Integer frontCid, UserInfo user, RecommenderItem recommenderItem, int expid, String os, String version, int index, int action) {
        StringBuilder url = new StringBuilder(defaultUrl);
        url.append("?t=rec.").append(rec_id);
        String _ref = "&m=OPEN_M2016-1";
        if (!StringUtils.isEmpty(os)) {
            if (os.toLowerCase().equals("ios")) {
                _ref = "&m=ios_m2016-1";
            } else if (os.toLowerCase().equals("android")) {
                _ref = "&m=android_m2016-1";
            } else if (os.toLowerCase().equals("h5")) {
                _ref = "&m=h5_m2016-1";
            } else if (os.toLowerCase().equals("pc")) {
                _ref = "&m=pc_m2016-1";
            }
        }
        url.append(_ref);
        if (user != null) {
            url.append("&pin=").append(user.getPin() == null ? "" : user.getPin());
            url.append("&uuid=").append(user.getUuid() == null ? "" : user.getUuid());
        }
        ClickStreamExtraValue clickStreamExtraValue = new ClickStreamExtraValue(0);
        if (spu != null) {
            clickStreamExtraValue.setSpu(spu);
        }
        if (spus != null && !spus.isEmpty()) {
            clickStreamExtraValue.setSpus(spus.toArray(new Long[spus.size()]));
        }
        if (frontCid != null) {
            clickStreamExtraValue.setFrontCid(frontCid);
        }
        List<Long> cspus = new ArrayList<Long>();
        List<Integer> ctopicIds = new ArrayList<Integer>();
        switch (recommenderItem.getRec_type()) {
            case 1 : cspus.add(((RecommenderSku) recommenderItem).getSpu()); break;
            case 2 : ctopicIds.add(((RecommenderTopic) recommenderItem).getTopic_id()); break;
            case 3 : break;
            case 4 : cspus.add(((RecommenderShopifyProduct) recommenderItem).getProduct_id()); break;
            default: break;
        }
        clickStreamExtraValue.setRec_type(recommenderItem.getRec_type());
        if (!cspus.isEmpty()) {
            clickStreamExtraValue.setCspus(cspus.toArray(new Long[cspus.size()]));
        }
        if (!ctopicIds.isEmpty()) {
            clickStreamExtraValue.setCtopicIds(ctopicIds.toArray(new Integer[ctopicIds.size()]));
        }
        if (!StringUtils.isEmpty(os)) {
            clickStreamExtraValue.setOs(os);
        }
        if (!StringUtils.isEmpty(version)) {
            clickStreamExtraValue.setVer(version);
        }
        clickStreamExtraValue.setExpid(expid);
        clickStreamExtraValue.setIndex(index);
        clickStreamExtraValue.setAction(action);
        url.append("&v=").append(JSONObject.toJSONString(clickStreamExtraValue));
        return url.toString();
    }

    /**
     * 生成完整的展示链接
     * @param rec_id
     * @param spu
     * @param spus
     * @param user
     * @param recommenderItems
     * @param expid
     * @param os
     * @param version
     * @param action
     * @return
     */
    private static String packageWholeImplUrl(String rec_id, Long spu, List<Long> spus, Integer frontCid, UserInfo user, List<RecommenderItem> recommenderItems, int expid, String os, String version, int action) {
        StringBuilder url = new StringBuilder(defaultUrl);
        url.append("?t=rec.").append(rec_id);
        String _ref = "&m=OPEN_M2016-1";
        if (!StringUtils.isEmpty(os)) {
            if (os.toLowerCase().equals("ios")) {
                _ref = "&m=ios_m2016-1";
            } else if (os.toLowerCase().equals("android")) {
                _ref = "&m=android_m2016-1";
            } else if (os.toLowerCase().equals("h5")) {
                _ref = "&m=h5_m2016-1";
            } else if (os.toLowerCase().equals("pc")) {
                _ref = "&m=pc_m2016-1";
            }
        }
        url.append(_ref);
        if (user != null) {
            url.append("&pin=").append(user.getPin() == null ? "" : user.getPin());
            url.append("&uuid=").append(user.getUuid() == null ? "" : user.getUuid());
        }
        ClickStreamExtraValue clickStreamExtraValue = new ClickStreamExtraValue(0);
        if (spu != null) {
            clickStreamExtraValue.setSpu(spu);
        }
        if (spus != null && !spus.isEmpty()) {
            clickStreamExtraValue.setSpus(spus.toArray(new Long[spus.size()]));
        }
        if (frontCid != null) {
            clickStreamExtraValue.setFrontCid(frontCid);
        }
        if (recommenderItems != null && !recommenderItems.isEmpty()) {
            List<Long> cspus = new ArrayList<Long>();
            List<Integer> ctopicIds = new ArrayList<Integer>();
            for (int i = 0; i < recommenderItems.size(); i++) {
                try {
                    RecommenderItem item = recommenderItems.get(i);
                    switch (item.getRec_type()) {
                        case 1 : cspus.add(((RecommenderSku) item).getSpu()); break;
                        case 2 : ctopicIds.add(((RecommenderTopic)item).getTopic_id()); break;
                        case 3 : break;
                        case 4 : cspus.add(((RecommenderShopifyProduct)item).getProduct_id()); break;
                        default: break;
                    }
                } catch (Exception e) {}
            }
            if (!cspus.isEmpty()) {
                clickStreamExtraValue.setCspus(cspus.toArray(new Long[cspus.size()]));
            }
            if (!ctopicIds.isEmpty()) {
                clickStreamExtraValue.setCtopicIds(ctopicIds.toArray(new Integer[ctopicIds.size()]));
            }
        }
        if (!StringUtils.isEmpty(os)) {
            clickStreamExtraValue.setOs(os);
        }
        if (!StringUtils.isEmpty(version)) {
            clickStreamExtraValue.setVer(version);
        }
        clickStreamExtraValue.setExpid(expid);
        clickStreamExtraValue.setAction(action);
        url.append("&v=").append(JSONObject.toJSONString(clickStreamExtraValue));
        return url.toString();
    }

    public static void main(String[] args) {
        RecommenderData<RecommenderItem> recommenderData = new RecommenderData<RecommenderItem>();
        List<RecommenderItem> recommenderItems = new ArrayList<RecommenderItem>();
        recommenderData.setExp_id(1);
        recommenderData.setList(recommenderItems);

        RecommenderShopifyProduct rec1 = new RecommenderShopifyProduct();
        rec1.setPos(0);
        rec1.setImage_url("https://cdn.shopify.com/s/files/1/1237/7790/products/HTB1ALzmHpXXXXbKXVXXq6xXFXXXL.jpeg?v=1461383837");
        rec1.setTitle("Mom Red Crystal Rose Heart Silver Necklace");
        rec1.setRec_type(4);
        rec1.setProduct_id(5777995137l);
        rec1.setPrice("19.50");
        rec1.setOrig_price("99.50");
        rec1.setDisplay("80% off");
        rec1.setW(0.1);

        RecommenderSku rec2 = new RecommenderSku();
        rec2.setMain_image_url("http://cdn.evermarker.com/media/catalog/product/cache/1/image/600x600/9df78eab33525d08d6e5fb8d27136e95/1/_/1_1176_7.jpg");
        rec2.setMain_title("Personalized Cross With Heart Unique 925 Sterling Silver Lover's Heart");
        rec2.setPos(1);
        rec2.setRec_type(1);
        rec2.setMain_sku(10000000l);
        rec2.setSpu(100000l);
        rec2.setW(0.2);
        recommenderItems.add(rec1);
        recommenderItems.add(rec2);

        FrontParam frontParam = new FrontParam();
        frontParam.setRec_id("100");
        frontParam.setCid(1);
        frontParam.setSpu(100000l);
        frontParam.setOs("IOS");
        frontParam.setVersion("2.3.2");
        System.out.println(JSONObject.toJSONString(recommenderData));
        MercuryUrlManager.setMercuryUrl(recommenderData, frontParam);
        System.out.println(JSONObject.toJSONString(recommenderData));
    }
}
